<?php

/*
	Class: Commerce_Plugins_Content

	About: Author
		Rich Joslin

	About: License
		<http://communit.as/docs/license>
*/
class Commerce_Plugins_Content {

	private $_cache;

	/* Group: Constructors */

	/*
		Function: __construct
	*/
	function __construct() {		
		if(Zend_Registry::isRegistered('memcache')){
			$this->_cache = Zend_Registry::get('memcache');				
		}			
	}

	/* Group: Instance Methods */

	/*
		Function: addCatalogNavTree
	*/
	function addCatalogNavTree($params) {
		memory_profiler("start Catalog Navigation Tree Plugin");
		
		$catalog_nav = null;
		$cacheKey = null;
		
		if(isset($this->_cache)){
			$cacheKey = "commerce_catalog_nav";						
			$catalog_nav = $this->_cache->load($cacheKey);				
		}
		
		if(empty($catalog_nav)){		
			$catalog_table = new CommerceMagentoCatalog();
			$tmp_catalog_nav = Commerce_Common::categoryTree(false, $params['locale_code']);
			$catalog_nav = array();
			foreach ($tmp_catalog_nav as $cat) {
				if ($cat['level'] == Cts_Registry::get("magento_root_category_level", "commerce")) {
	
					// TODO - factor this out into a separate function in some model
	
					$category = $catalog_table->getCategory($cat['category_id']);
					if (array_key_exists('blackdiamond_swiftcollective_related_categories', $category) && $category['blackdiamond_swiftcollective_related_categories'] != '') {
						$related = explode(",", $category['blackdiamond_swiftcollective_related_categories']);
						$rel_cats = array();
						foreach ($related as $catid) {
							$tmp_cat = $catalog_table->getCategory($catid);
							$rel_cats[] = array(
								'url' => "/shop/".$category['url_key']."/".$tmp_cat['url_key'],
								'name' => $tmp_cat['name'],
							);
						}
						$cat['rel_cats'] = $rel_cats;
					}
					$subcategories = array();
					foreach ($cat['children'] as $subcategory) {
						$tmp_subcategory = $catalog_table->getCategory($subcategory['category_id']);
						$subcategory['url_key'] = $tmp_subcategory['url_key'];
						$subcategories[] = $subcategory;
					}
					$cat['children'] = $subcategories;
					// $cat['url_key'] = $category['url_key'];
					$catalog_nav[] = $cat;
				}
			}
			
			if(isset($this->_cache)){
				$this->_cache->save($catalog_nav,$cacheKey);				
			}
		
		}
		
		$params['nav_items']['frontend_catalog'] = $catalog_nav;
		
		memory_profiler("end Catalog Navigation Tree Plugin");
		
		return $params;
	}

}
